<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="httpUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <el-progress v-show="showProgress" type="circle" :percentage="percent" class="progress" />
  </el-upload>
</template>

<script>
const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDqVu2tTmpb6KHxNVNyIMAiz0kDOIvHMBj', // 身份识别ID
  SecretKey: 'JL6aolTu4xZv0oLaZHislNimfLksjJcj' // 身份秘钥
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      percent: 0,
      showProgress: false
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    httpUpload(res) {
      console.log(res.file)
      this.showProgress = true
      cos.putObject({
        Bucket: 'gengdonghua-1313016031', /* 存储桶 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: res.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: res.file, // 上传文件对象
        // 图片上传的过程中不断执行的回调函数 这里可以做上传进度相关的功能
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        // 上传成功或者失败都会执行这个回调
        console.log(err, data)
        this.imageUrl = `https://${data.Location}`
        this.showProgress = false
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background: #fff;
}
</style>
